package com.example.myapplication.old;

import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.myapplication.activity.LoadingActivity;
import com.example.myapplication.R;
import com.example.myapplication.api.MusicApiService;
import com.example.myapplication.entity.HotSongs;
import com.example.myapplication.entity.Song;
import com.example.myapplication.tools.BarTransparent;
import com.example.myapplication.tools.Lrc;
import com.lauzy.freedom.library.LrcView;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import jp.wasabeef.glide.transformations.BlurTransformation;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SongDetailActivity extends AppCompatActivity {
    private ImageButton start;
    private ImageButton skip_pre;
    private ImageButton skip_next;
    private MediaPlayer mediaPlayer;
    private ImageView img_al;
    private TextView song_name;
    private HotSongs hotSongs;
    private View container;
    private TextView singer_name;
    private TextView song_desc;
    private SeekBar seekBar;
    private Timer timer;
    private TextView start_time;
    private TextView finish_time;
    private TextView back;
    private Animation rotateAnimation;
    private ObjectAnimator objectAnimator;
    public static final int STATE_PLAYING =1;//正在播放
    public static final int STATE_PAUSE =2;//暂停
    public static final int STATE_STOP =3;//停止
    public int state = STATE_STOP;
    private LrcView lrcView;
    float x1 = 0;
    float x2 = 0;
    float y1 = 0;
    float y2 = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarTransparent.makeStatusBarTransparent(this);
        setContentView(R.layout.activity_test1);
        init();
        loadData(hotSongs.getId());
        initLrc(hotSongs.getId());
    }




    private void initMediaPlayer(String mp3url) {
        try {
            if(mp3url==null){
                mp3url = "http://m8.music.126.net/20210507211457/783c4c69a62064ffdc56cc17e2ca149b/ymusic/0fd6/4f65/43ed/a8772889f38dfcb91c04da915b301617.mp3";
            }
            mediaPlayer.setDataSource(mp3url);
            mediaPlayer.prepare();
            seekBar.setMax(mediaPlayer.getDuration());
            int s = mediaPlayer.getDuration() / 1000;
            String total = s / 60 + ":" + s % 60;
            finish_time.setText(total);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void init() {
        skip_pre = findViewById(R.id.skip_pre);
        skip_next = findViewById(R.id.skip_next);
        start = findViewById(R.id.start);
        start.setOnClickListener(this::onClick);
        mediaPlayer = new MediaPlayer();
        song_name = findViewById(R.id.song_name);
        img_al = findViewById(R.id.img_al);
        container = findViewById(R.id.container);
        singer_name = findViewById(R.id.singer_name);
        song_desc  = findViewById(R.id.song_desc);
        seekBar = findViewById(R.id.seek_bar);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());
        start_time = findViewById(R.id.start_time);
        finish_time = findViewById(R.id.finish_time);
        back = findViewById(R.id.back);
        lrcView = findViewById(R.id.lrcView);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //图片旋转
        objectAnimator = ObjectAnimator.ofFloat(img_al, "rotation", 0f, 360f);
        objectAnimator.setDuration(35000);//设定转一圈的时间
        objectAnimator.setInterpolator(new LinearInterpolator());
        objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);//设定无限循环
        objectAnimator.setRepeatMode(ObjectAnimator.RESTART);


        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        hotSongs = (HotSongs) bundle.getSerializable("song");
        String alName = hotSongs.getAl().getName();
        String songName = hotSongs.getName();
        String singerName = hotSongs.getAr().get(0).getName();
        if(alName==null){
            alName = "null";
        }
        if(songName==null){
            songName = "null";
        }
        if(singerName==null){
            singerName = "null";
        }
        song_desc.setText(songName+"-"+singerName+"-"+alName);
        song_name.setText(songName);
        singer_name.setText(singerName);
        String url = hotSongs.getAl().getPicUrl();


        start_time.setText("0:0");
        //设置虚化的背景图片
        RequestOptions options= RequestOptions
                .bitmapTransform(new BlurTransformation(90, 5));
        SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                container.setBackground(resource);
            }
        };
        Glide.with(this)
                .load(url)
                .apply(options)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(simpleTarget);

        RoundedCorners roundedCorners= new RoundedCorners(30);
        RequestOptions options1= RequestOptions
                .bitmapTransform(roundedCorners)
                .circleCrop();
        Glide.with(this).load(url)
                .centerCrop()
                .error(R.drawable.ic_baseline_refresh_24)
                .placeholder(R.drawable.ic_baseline_refresh_24)
                .apply(options1)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(img_al);

        lrcView.setOnPlayIndicatorLineListener(new LrcView.OnPlayIndicatorLineListener() {
            @Override
            public void onPlay(long time, String content) {
                mediaPlayer.seekTo((int) time);
            }
        });
    }


    public void onClick(View v) {
                if(state == STATE_STOP){
                    objectAnimator.start();//动画开始
                    state = STATE_PLAYING;
                }
                else if(state == STATE_PAUSE){
                    objectAnimator.resume();//动画重新开始
                    state = STATE_PLAYING;
                }
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                    start.setImageResource(R.drawable.ic_baseline_pause_24);
                    //定时器每秒钟更改进度条
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                                seekBar.setProgress(mediaPlayer.getCurrentPosition());

                        }
                    },0,1000);
                }
                else{
                    mediaPlayer.pause();
                    start.setImageResource(R.drawable.ic_baseline_play_arrow_24);
                    timer.cancel();
                    if(state == STATE_PLAYING){
                        objectAnimator.pause();//动画暂停
                        state = STATE_PAUSE;
                    }
                }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        objectAnimator.end();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        if(timer!=null)
        timer.cancel();
    }

    private void loadData(int id){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://autumnfish.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        MusicApiService service =  retrofit.create(MusicApiService.class);

        Call<Song> call = service.getSong(LoadingActivity.cookie,id);
        call.enqueue(new Callback<Song>() {
            @Override
            public void onResponse(Call<Song> call, Response<Song> response) {
                Song baseResponse = response.body();
                String mp3Url =  baseResponse.getData().get(0).getUrl();
                initMediaPlayer(mp3Url);
            }
            @Override
            public void onFailure(Call<Song> call, Throwable t) {

                t.printStackTrace();
            }

        });
    }

    private void initLrc(int id) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://autumnfish.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        MusicApiService service =  retrofit.create(MusicApiService.class);

        Call<com.example.myapplication.entity.Lrc> call = service.getLrc(id);
        call.enqueue(new Callback<com.example.myapplication.entity.Lrc>() {
            @Override
            public void onResponse(Call<com.example.myapplication.entity.Lrc> call, Response<com.example.myapplication.entity.Lrc> response) {
                com.example.myapplication.entity.Lrc baseResponse = response.body();
                String path = getApplicationContext().getFilesDir().getPath().toString()+"/song.lrc";
                File file = new File(path);
                try {
                    if(!file.exists()){
                        file.createNewFile();
                    }
                    else{
                        file.delete();
                        file.createNewFile();
                    }
                    FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
                    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
                    bufferedWriter.write(baseResponse.getLrc().getLyric());
                    bufferedWriter.close();
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                List<com.lauzy.freedom.library.Lrc> lrcs = Lrc.parseLrcFromFile(file);
                lrcView.setLrcData(lrcs);
                lrcView.setEmptyContent("暂时找不到歌词");

            }

            @Override
            public void onFailure(Call<com.example.myapplication.entity.Lrc> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        //进度条改变时
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            lrcView.updateTime(mediaPlayer.getCurrentPosition());
            int s = mediaPlayer.getCurrentPosition() / 1000;
            String total = s / 60 + ":" + s % 60;
            start_time.setText(total);
            //处理音乐播放结束时
            if(progress>=seekBar.getMax() && mediaPlayer.isPlaying()){
                timer.cancel();
                objectAnimator.pause();//动画暂停
                state = STATE_PAUSE;
                start.setImageResource(R.drawable.ic_baseline_play_arrow_24);
                seekBar.setProgress(0);
                start_time.setText("0:0");
            }
        }

        //接触进度条时
        public void onStartTrackingTouch(SeekBar seekBar) {
        }
        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            mediaPlayer.seekTo(seekBar.getProgress());
            int s = mediaPlayer.getCurrentPosition() / 1000;
            String total = s / 60 + ":" + s % 60;
            start_time.setText(total);
        }
    }
}